// 实现这个项目的构建任务

const { src,dest,series,parallel,watch } = require('gulp');
const loadPlugin=require('gulp-load-plugins')();
const del=require('del');
const browsersync=require('browser-sync')
// const sass=require('gulp-sass')
// const csso=require("gulp-csso")
// const babel=require('gulp-babel')
// const uglify=require('gulp-uglify')
// const swig=require('gulp-swig')
// const imagemin=require("gulp-imagemin");
// const useref = require('gulp-useref');
const bs=browsersync.create()

const data={
  pkg:require('./package.json'),
  date:new Date()
}

const html=()=>{
  return src('src/**/*.html',{base:'src'})
  .pipe(loadPlugin.swig({data,cache:false}))
  .pipe(dest('dist'))
}
const public=()=>{
  return src('public/**',{base:'public'})
  .pipe(dest('dist'))
}
const useref=()=>{
  return src('dist/**',{base:'dist'})
    .pipe(loadPlugin.useref({searchPath:['dist','.']}))
    .pipe(dest('dist'))
}
const css=()=>{
  return src('src/assets/styles/*.scss',{base:'src'})
   .pipe(loadPlugin.sass({outputStyle:'expanded'}))
   .pipe(loadPlugin.csso())
  .pipe(dest('dist'))
}
const js=()=>{
 return  src('src/assets/scripts/*.js',{base:'src'})
 .pipe(loadPlugin.babel({presets:['@babel/preset-env']}))
 .pipe(loadPlugin.uglify())
 .pipe(dest('dist'))
}
//处理图片和字体文件
const image=()=>{
  return src('src/assets/**/*.{svg,png,eot,ttf,woff}',{base:'src'})
  .pipe(loadPlugin.imagemin())
  .pipe(dest('dist'))
}

//定义清除任务
const clear=()=>{
  return del(['dist'])
 }

const sever=()=>{
  watch('src/**/*.js',js)
  watch('src/**/*.scss',css)
  watch('src/**/*.html',html)
  watch('src/*.html',html)

  bs.init({
    // notify:true,
    // port:3000,
    // open:true,
    files:'dist/**',//监听dist目录下变化
    server: {
      baseDir:['dist','src','public'],
      // routes:{
      //   "/node_modules":'node_modules'
      // }
    }
  })
}
const hotUpdate=series(parallel(html,public,css,js,image),useref) 
const develop=series(clear,hotUpdate,sever)
const build=series(clear,hotUpdate)



module.exports={
  clear,
  develop,
  build,
}